<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\helpers\v1\traits\SearchDataForModel;
use app\api\model\v1\AdminLog;
use app\api\model\v1\Admins;
use app\api\model\v1\AuthRule;
use app\api\model\v1\GatherCompany;
use app\api\model\v1\Project;
use app\api\model\v1\ProjectSample;
use app\api\model\v1\RectifyAndReformRules;
use app\BaseController;
use think\Request;

class Unit extends BaseController
{

    use SearchDataForModel;

    /**
     * Created by PhpStorm.
     * User: 刘海龙
     * Date: 2022/1/3
     * Time: 13:13
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 责任单位
     */
    public function getUnitList()
    {
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);
        $is_page = $this->request->param('is_page', 'page');
        $map = [];
        if ($this->request->has('type') && !empty($this->request->param('type'))) {
            $map[] = ['type', '=', $this->request->param('type')];
        }
        if ($is_page === 'no_page') {
            $res = GatherCompany::field('id as value,gather_company_title as label')->where(['type' => 2])->select();
        }else if ($is_page === 'radio'){
            $res = GatherCompany::field('id,gather_company_title')->where($map)->select();
        } else {
            $data = GatherCompany::where($map)->select()->toArray();
            $tree_res = AuthRule::sortMenu($data);
            $count = count($tree_res);//总条数
            $start=($page-1)*$limit;//偏移量，当前页-1乘以每页显示条数
            $new_arr = array_slice($tree_res,$start,$limit);
            $res = [
                'count'=>$count,
                'data'=>$new_arr
            ];
        }
        return $this->response($res);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/4 13:35
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 责任单位用户
     */
    public function getUnitAdmin()
    {
        $unit_id = $this->request->param('unit_id', 0);
        $res = Admins::field('id as value,username as label')->where(['unit_id' => $unit_id])->select();
        return $this->response($res);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/12 9:34
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 微信端单位列表
     */
    public function getWxCompanyList(){
        $limit = $this->request->param('limit', 10);
        $map = [];
        if ($this->request->has('type') && !empty($this->request->param('type'))) {
            $map[] = ['type', '=', $this->request->param('type')];
        }
        $res = GatherCompany::where($map)->paginate($limit);
        return $this->response($res);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/4 16:08
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 验证
     */
    public function getCheckProject()
    {
        $data = $this->request->param();
        $res = Project::field('id,single')->whereIn('id', $data['project_ids'])->select()->toArray();
        $new_arr = [];
        foreach ($res as $key => $v) {
            $new_arr[] = $v['single'];
        }
        if (in_array("1", $new_arr)) {
            if (count($new_arr) > 1) {
                return $this->response(403, '选项中包含唯一项目');
            } else {
                return $this->response();
            }
        } else {
            return $this->response();
        }
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/4 17:25
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存社区规则
     */
    public function saveCommunityGz()
    {
        $data = $this->request->param();
        $single = $this->request->param('single');
        $community_id = $data['community_id'];
        $project_ids = $data['project_id'];
        if (intval($single) === 1) {
            $res = Project::with(['target' => function ($query) {
                $query->field('id,project_id');
                return $query;
            }, 'sample' => function ($sample) use ($community_id) {
                $sample->field('id,project_id')->where(['community_id' => $community_id]);
                return $sample;
            }])->whereIn('id', $project_ids)->select()->each(function ($item, $key) {
                if ($item['target']) {
                    $target_ids = '';
                    foreach ($item['target'] as $k => $v) {
                        $target_ids .= $v['id'] . ',';
                    }
                    $item['target_ids'] = rtrim($target_ids, ',');

                }
                if ($item['sample']) {
                    $sample_ids = '';
                    foreach ($item['sample'] as $k => $v) {
                        $sample_ids .= $v['id'] . ',';
                    }
                    $item['sample_ids'] = rtrim($sample_ids, ',');

                }
                return $item;
            })->toArray();
            foreach ($res as $key => $v) {
                //规则数组
                $gz = [
                    'unit_id' => $data['unit_id'], //单位
                    'admin_id' => $data['admin_id'], //用户
                    'community_id' => $data['community_id'], //社区
                    'project_id' => $v['id'], //项目
                    'target_ids' => $v['target_ids'], //指标字符串
                    'sample_ids' => $v['sample_ids'], //样本点字符串
                ];
                RectifyAndReformRules::create($gz);
            }
        } else {
            //根据样本点循环
            foreach ($data['sample_id'] as $k=>$value){
                $res = ProjectSample::find($value);
                if (!is_null($res)){
                    $roads_gz = [
                        'unit_id' => $data['unit_id'], //单位
                        'admin_id' => $data['admin_id'], //用户
                        'community_id' => $res->community_id, //社区
                        'project_id' => $data['project_id'], //项目
                        'single' => $single,
                        'target_ids' => implode(',', $data['target_id']), //指标字符串
                        'sample_ids' => $value, //样本点字符串
                    ];
                    RectifyAndReformRules::create($roads_gz);
                }

            }
//            foreach ($data['community_id'] as $k => $value) {
//                //规则数组
//                $roads_gz = [
//                    'unit_id' => $data['unit_id'], //单位
//                    'admin_id' => $data['admin_id'], //用户
//                    'community_id' => $value, //社区
//                    'project_id' => $data['project_id'], //项目
//                    'single' => $single,
//                    'target_ids' => implode(',', $data['target_id']), //指标字符串
//                    'sample_ids' => implode(',', $data['sample_id']), //样本点字符串
//                ];
//                RectifyAndReformRules::create($roads_gz);
//            }
        }
        AdminLog::record('保存社区规则', [], $this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/4 16:58
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取规则
     */
    public function getReformRules()
    {
        $data = $this->request->param();

        $res = RectifyAndReformRules::with(['admin', 'unit'])->where(['community_id' => $data['community_id'], 'project_id' => $data['project_id']])->whereFindInSet('target_ids', $data['target_id'])->whereFindInSet('sample_ids', $data['sample_id'])->select();
        if($res->isEmpty()){
            return $this->response(403,'暂无信息');
        }else{
            return $this->response($res->toArray());
        }

    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/1/4 18:02
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 渲染整改规则
     */
    public function getRectifyAndReformRulesInfo()
    {
        $limit = $this->request->param('limit', 10);
        if ($this->request->has('type') && !empty($this->request->param('type'))) {
            $map[] = ['single', '=', $this->request->param('type')];
        }
        $res = RectifyAndReformRules::with(['admin', 'unit', 'community', 'project'])->where($map)->order('id desc')->paginate($limit)->each(function ($item,$key){
            $sample_arr = explode(',',$item['sample_ids']);
            $sample = ProjectSample::field('id,sample_title')->where('id','in',$sample_arr)->select()->toArray();
            $str_sample_name= '';
            foreach ($sample as $k=>$v){
                $str_sample_name .= $v['sample_title'].',';
            }
            $item['str_sample_name'] = rtrim($str_sample_name,',');;
            return $item;
        });
        return $this->response($res);
    }
}
